package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.CartItemEntity;
import com.example.HaiDLaobackend.entity.ProductEntity;
import com.example.HaiDLaobackend.service.CartItemService;
import com.example.HaiDLaobackend.service.ProductService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    private final CartItemService cartItemService;
    private final ProductService productService;

    public CartController(CartItemService cartItemService, ProductService productService) {
        this.cartItemService = cartItemService;
        this.productService = productService;
    }

    public static class CartModifyRequest {
        @NotNull
        private Long productId;
        @Min(1)
        private Integer quantity;
        public Long getProductId() { return productId; }
        public void setProductId(Long productId) { this.productId = productId; }
        public Integer getQuantity() { return quantity; }
        public void setQuantity(Integer quantity) { this.quantity = quantity; }
    }

    @PostMapping("/add")
    @Transactional
    public ApiResponse<?> add(@Valid @RequestBody CartModifyRequest body, @RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) return ApiResponse.error("未登录");
        ProductEntity prod = productService.getById(body.getProductId());
        if (prod == null || prod.getStatus() == null || prod.getStatus() == 0) {
            return ApiResponse.error("商品不存在或已下架");
        }
        CartItemEntity exist = cartItemService.getOne(new LambdaQueryWrapper<CartItemEntity>()
            .eq(CartItemEntity::getUserId, currentUserId)
            .eq(CartItemEntity::getProductId, body.getProductId()));
        if (exist == null) {
            CartItemEntity item = new CartItemEntity();
            item.setUserId(currentUserId);
            item.setProductId(body.getProductId());
            item.setQuantity(body.getQuantity());
            cartItemService.save(item);
        } else {
            exist.setQuantity(exist.getQuantity() + body.getQuantity());
            cartItemService.updateById(exist);
        }
        return ApiResponse.ok(null);
    }

    @PostMapping("/update")
    public ApiResponse<?> update(@Valid @RequestBody CartModifyRequest body, @RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) return ApiResponse.error("未登录");
        CartItemEntity exist = cartItemService.getOne(new LambdaQueryWrapper<CartItemEntity>()
            .eq(CartItemEntity::getUserId, currentUserId)
            .eq(CartItemEntity::getProductId, body.getProductId()));
        if (exist == null) {
            return ApiResponse.error("购物车中不存在该商品");
        }
        exist.setQuantity(body.getQuantity());
        cartItemService.updateById(exist);
        return ApiResponse.ok(null);
    }

    @PostMapping("/remove")
    public ApiResponse<?> remove(@RequestParam Long productId, @RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) return ApiResponse.error("未登录");
        cartItemService.remove(new LambdaQueryWrapper<CartItemEntity>()
            .eq(CartItemEntity::getUserId, currentUserId)
            .eq(CartItemEntity::getProductId, productId));
        return ApiResponse.ok(null);
    }

    @GetMapping("/list")
    public ApiResponse<Map<String, Object>> list(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) return ApiResponse.error("未登录");
        List<CartItemEntity> items = cartItemService.list(new LambdaQueryWrapper<CartItemEntity>()
            .eq(CartItemEntity::getUserId, currentUserId));
        BigDecimal total = items.stream().map(i -> {
            ProductEntity p = productService.getById(i.getProductId());
            if (p == null) return BigDecimal.ZERO;
            return p.getPrice().multiply(BigDecimal.valueOf(i.getQuantity()));
        }).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String, Object> data = new HashMap<>();
        data.put("items", items);
        data.put("totalAmount", total);
        return ApiResponse.ok(data);
    }
}


